package ntd.util.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.Map;

public class UtilRsa {

    public static final String preKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAL4MYK+2iQryqN3hFIiMNlzZD75SU/yTwehUfmLQhzB2o0QAxPZHzrqGGKObp9PYZqwxMm4BPFRgnPFmttABGMXZAzkBGTsfwrN+mxUNPLbGmLRhyv7drthBw9bsWa0Oh9MCZn37kKmQ1dUSCgD/6Gp6ol9z5S2KsgBNxJb3kRQPAgMBAAECgYA+IwbjvH8vJKrArMxNXuaRUej7VaifHuJZ53JRNZPV7Rwxajz7tvuo8ZoRuB1Vvt3G8+jknaPPhK0bonUoKguiZ8HD+jkGwZ6OsrE4Tm3djM6Kj5KLW/hXQRgqcuIADleBb5sHaWB0/H3f21WpdhfVvONZ0CVxY1yAnGsujUsWbQJBAO7a5vxwVw/agVoQ9CfFpeKq7Mu+bvVimUznFhAROOc0Dg1xJyilqOiUfITcT7Q9ZcB/u7+yyeOsHIzEObxP45MCQQDLsJ+5LUdcLjoYvJTxvq2Zvb9LGkW+ng7gIPjC2pfoXtE4Kwkymu17hThZ4feevuss2hTSFHFrA2GNttvnEpMVAkBrg+WNpBPMcxLes9rzPCibi0zjuWjA1A0lbK+ls9rlV60rp890oH0TlCMouvK1sx1mNRkSBSyTaxm+02UZuuw5AkA4qx30zdURn0bIhQbHLu5rXG/w/BE1VBH9Zw7uXxRuMJryjn6TlqjFea3Qy94xSxpwsweh3tAjHqCwZZROeEt1AkBLstvv8Vgh47UEJvR3M3GpydUmwutNqYSILBE/QOTtSSyxjT2xAWy07LdjlSriJyJCBY9RNnfr0Gd0BYBZdj9M";

    public static final String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+DGCvtokK8qjd4RSIjDZc2Q++UlP8k8HoVH5i0IcwdqNEAMT2R866hhijm6fT2GasMTJuATxUYJzxZrbQARjF2QM5ARk7H8KzfpsVDTy2xpi0Ycr+3a7YQcPW7FmtDofTAmZ9+5CpkNXVEgoA/+hqeqJfc+UtirIATcSW95EUDwIDAQAB";

    private static RSA rsa = new RSA(UtilRsa.preKey, UtilRsa.pubKey);

    /**
     * 数据签名
     * @param map
     * @return
     */
    public static String sign(Map<String, String> map) {
        String data = MapUtil.sortJoin(map, ",", ":", true);
        return rsa.encryptHex(SecureUtil.md5(data).substring(12, 48), KeyType.PrivateKey);
    }

    /**
     * 加密
     * @param obj
     * @return
     */
    public static String encryption(Object obj, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.encryptBase64(JSONUtil.toJsonStr(obj), KeyType.PublicKey);
    }

    /**
     * 解密算法
     * @param publicKey
     * @return
     */
    public static JSONObject decryptStr(String data, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return JSONUtil.parseObj(rsa.decryptStr(data, KeyType.PublicKey));
    }

}
